<template>
  <div>
    <div class="query-form">
      <el-form :model="queryForm" inline ref="queryFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请输入角色名称"
            v-model="queryForm.roleName"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('queryFormRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="menu-btn">
        <el-button type="primary" @click="handleAdd()" v-has="'role-add'">创建</el-button>
      </div>
      <el-table :data="roleList" style="width: 100%" row-key="_id">
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :label="item.label"
          :prop="item.prop"
          :formatter="item.formatter"
        />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
             v-has="'role-edit'"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="handleSetting(scope.row)"
               v-has="'role-set'"
              >设置权限</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row._id)"
               v-has="'role-delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <el-dialog
      v-model="roleAddDialog"
      :title="action == 'create' ? '角色新增' : '角色编辑'"
      :before-close="handleAddClose"
    >
      <el-form
        :model="dialogForm"
        label-width="100px"
        ref="dialogFormRef"
        :rules="rules"
      >
        <el-form-item prop="roleName" label="角色名称" required>
          <el-input
            v-model="dialogForm.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input
            type="textarea"
            :rows="2"
            v-model="dialogForm.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm(1)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="settingDialog"
      title="设置权限"
      :before-close="handleSetClose"
    >
      <el-form
        :model="settingDialogForm"
        label-width="100px"
        ref="setDialogFormRef"
      >
        <el-form-item prop="roleName" label="角色名称">
          <el-input v-model="setDialogForm.roleName" readonly></el-input>
        </el-form-item>
        <el-form-item prop="permission" label="选择权限">
          <el-tree
            :data="menuList"
            show-checkbox
            node-key="_id"
            :props="{ label: 'menuName' }"
            default-expand-all
            ref="permissionTree"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleSetClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm(2)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import utils from "../../utils/utils";
export default {
  name: "Role",
  data() {
    return {
      pager: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      queryForm: {
        roleName: "",
      },
      roleList: [],
      columns: [
        { label: "角色名称", prop: "roleName" },
        { label: "备注", prop: "remark" },
        {
          label: "权限列表",
          prop: "permissionList",
          formatter: (row, col, value) => {
            let names = [];
            let list = value.halfCheckedKeys || [];
            list.map((key) => {
              if (key && this.actionMap[key]) {
                names.push(this.actionMap[key]);
              }
            });
            return names.join(",");
          },
        },
        {
          label: "创建时间",
          prop: "createTime",
          formatter(row, col, value) {
            return utils.formateDate(new Date(value));
          },
        },
      ],
      roleAddDialog: false,
      action: "create",
      dialogForm: {},
      dialogMode: 1, //菜单:1,按钮:2
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在2-8个字符", trigger: "blur" },
        ],
      },
      settingDialog: false,
      setDialogForm: {},
      menuList: null,
      settingDialogForm: {},
      actionMap: {},
      curRoleId: "",
    };
  },
  mounted() {
    this.getRoleList();
    this.getMenuList();
  },
  methods: {
    // 处理分页变化
    handleCurrentChange(current) {
      this.pager.pageNum = current;
      this.getRoleList();
    },

    handleQuery() {
      this.getRoleList();
    },
    handleAdd() {
      this.action = "create";
      this.roleAddDialog = true;
    },
    handleSetting(row) {
      this.settingDialog = true;
      this.curRoleId = row._id;
      this.curRoleName = row.roleName;
      const { checkedKeys } = row.permissionList;
      setTimeout(() => {
        this.$refs.permissionTree.setCheckedKeys(checkedKeys);
      }, 100);
      this.$nextTick(() => {
        Object.assign(this.setDialogForm, row);
      });
    },
    handleReset(form) {
      this.$refs[form].resetFields();
      this.getRoleList();
    },
    async handleDelete(id) {
      let res = await this.$api.rolesOperate({ _id: id, action: "delete" });
      this.$message.success("删除成功");
      this.getRoleList();
    },
    handleEdit(row) {
      this.action = "edit";
      this.roleAddDialog = true;
      this.$nextTick(() => {
        Object.assign(this.dialogForm, row);
      });
      this.getRoleList();
    },
    handleAddClose() {
      this.handleReset("dialogFormRef");
      this.roleAddDialog = false;
    },
    handleSetClose() {
      this.handleReset("setDialogFormRef");
      this.settingDialog = false;
    },

    async getRoleList() {
      let { list, page } = await this.$api.getRoleList({
        ...this.queryForm,
        ...this.pager,
      });
      this.roleList = list;
      this.pager = page;
    },
    handleMenuTypeChange(type) {
      this.dialogMode = type;
    },
    async handleConfirm(index) {
      if (index == 1) {
        this.$refs.dialogFormRef.validate(async (valid) => {
          if (valid) {
            let { action, dialogForm } = this;
            let params = { ...dialogForm, action };
            let res = await this.$api.rolesOperate(params);
            if (res) {
              this.roleAddDialog = false;
              this.$message.success("操作成功");
              this.handleReset("dialogFormRef");
              this.getRoleList();
            }
          }
        });
      } else if (index == 2) {
        let nodes = this.$refs.permissionTree.getCheckedNodes();
        let halfKeys = this.$refs.permissionTree.getHalfCheckedKeys();
        let checkedKeys = [];
        let parentKeys = [];
        nodes.map((node) => {
          if (!node.children) {
            checkedKeys.push(node._id);
          } else {
            parentKeys.push(node._id);
          }
        });

        let params = {
          _id: this.curRoleId,
          permissionList: {
            checkedKeys,
            halfCheckedKeys: parentKeys.concat(halfKeys),
          },
        };

        await this.$api.updatePermission(params);
        this.settingDialog = false;
        this.$message.success("设置成功");
        this.getRoleList();
      }
    },

    async getMenuList() {
      let list = await this.$api.getMenuList(this.menuForm);
      this.menuList = list;
      this.getActionMap(list);
    },

    getActionMap(list) {
      let actionMap = {};
      const deep = (arr) => {
        while (arr.length) {
          let item = arr.pop();
          if (item.children && item.action) {
            actionMap[item._id] = item.menuName;
          }
          if (item.children && !item.action) {
            deep(item.children);
          }
        }
      };
      deep(JSON.parse(JSON.stringify(list)));
      this.actionMap = actionMap;
    },
  },
};
</script>

<style lang="scss">
.menu-btn {
  padding: 20px;
}
</style>